import React, { useState, useEffect } from 'react'
import { Card, Table, Button, Modal, Form, Input, Select, DatePicker, Tag, Space, message, QRCode } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, QrcodeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons'
import MainLayout from '../components/layout/MainLayout'
import { visitorsAPI } from '../utils/api'
import dayjs from 'dayjs'

const { Option } = Select
const { RangePicker } = DatePicker

interface Visitor {
  id: string
  name: string
  phone: string
  company: string
  visitPurpose: string
  visitee: string
  visitTime: [string, string]
  status: 'pending' | 'approved' | 'rejected' | 'completed'
  qrCode: string
  idCard?: string
  vehiclePlate?: string
}

export default function Visitors() {
  const [visitors, setVisitors] = useState<Visitor[]>([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [qrModalVisible, setQrModalVisible] = useState(false)
  const [editingRecord, setEditingRecord] = useState<Visitor | null>(null)
  const [selectedVisitor, setSelectedVisitor] = useState<Visitor | null>(null)
  const [form] = Form.useForm()

  const fetchVisitors = async () => {
    setLoading(true)
    try {
      const response = await visitorsAPI.getList()
      setVisitors(response.data)
    } catch (error) {
      message.error('获取访客列表失败')
      console.error('Fetch visitors error:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchVisitors()
  }, [])

  const columns = [
    {
      title: '访客姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '来访公司',
      dataIndex: 'company',
      key: 'company'
    },
    {
      title: '访问目的',
      dataIndex: 'visitPurpose',
      key: 'visitPurpose'
    },
    {
      title: '被访人',
      dataIndex: 'visitee',
      key: 'visitee'
    },
    {
      title: '访问时间',
      dataIndex: 'visitTime',
      key: 'visitTime',
      render: (time: [string, string]) => (
        <div>
          <div>{time[0]}</div>
          <div>{time[1]}</div>
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          pending: { color: 'orange', text: '待审核' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已拒绝' },
          completed: { color: 'blue', text: '已完成' }
        }
        const config = statusMap[status as keyof typeof statusMap]
        return <Tag color={config.color}>{config.text}</Tag>
      }
    },
    {
      title: '二维码',
      dataIndex: 'qrCode',
      key: 'qrCode',
      render: (qrCode: string, record: Visitor) => (
        <Button 
          type="link" 
          icon={<QrcodeOutlined />}
          onClick={() => showQRCode(record)}
          disabled={record.status !== 'approved'}
        >
          {qrCode}
        </Button>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Visitor) => (
        <Space>
          {record.status === 'pending' && (
            <>
              <Button 
                type="link" 
                icon={<CheckOutlined />}
                onClick={() => handleApprove(record.id)}
                style={{ color: 'green' }}
              >
                通过
              </Button>
              <Button 
                type="link" 
                icon={<CloseOutlined />}
                onClick={() => handleReject(record.id)}
                danger
              >
                拒绝
              </Button>
            </>
          )}
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  const handleAdd = () => {
    setEditingRecord(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (record: Visitor) => {
    setEditingRecord(record)
    form.setFieldsValue({
      ...record,
      visitTime: [dayjs(record.visitTime[0]), dayjs(record.visitTime[1])]
    })
    setModalVisible(true)
  }

  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条访客记录吗？',
      onOk: async () => {
        try {
          await visitorsAPI.delete(id)
          message.success('删除成功')
          fetchVisitors()
        } catch (error) {
          message.error('删除失败')
        }
      }
    })
  }

  const handleApprove = async (id: string) => {
    try {
      await visitorsAPI.approve(id)
      message.success('审核通过')
      fetchVisitors()
    } catch (error) {
      message.error('操作失败')
    }
  }

  const handleReject = async (id: string) => {
    try {
      await visitorsAPI.reject(id)
      message.success('已拒绝')
      fetchVisitors()
    } catch (error) {
      message.error('操作失败')
    }
  }

  const showQRCode = (visitor: Visitor) => {
    setSelectedVisitor(visitor)
    setQrModalVisible(true)
  }

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)

      const formattedValues = {
        ...values,
        visitTime: [
          values.visitTime[0].format('YYYY-MM-DD HH:mm'),
          values.visitTime[1].format('YYYY-MM-DD HH:mm')
        ]
      }

      if (editingRecord) {
        await visitorsAPI.update(editingRecord.id, formattedValues)
        message.success('更新成功')
      } else {
        await visitorsAPI.create(formattedValues)
        message.success('添加成功')
      }

      setModalVisible(false)
      form.resetFields()
      setEditingRecord(null)
      fetchVisitors()
    } catch (error) {
      message.error('操作失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <MainLayout>
      <Card 
        title="访客管理" 
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增访客
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={visitors}
          rowKey="id"
          loading={loading}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
      </Card>

      {/* 访客编辑/新增模态框 */}
      <Modal
        title={editingRecord ? '编辑访客' : '新增访客'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setModalVisible(false)
          form.resetFields()
          setEditingRecord(null)
        }}
        width={600}
        confirmLoading={loading}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="访客姓名"
            rules={[{ required: true, message: '请输入访客姓名' }]}
          >
            <Input placeholder="请输入访客姓名" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="联系电话"
            rules={[
              { required: true, message: '请输入联系电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
            ]}
          >
            <Input placeholder="请输入联系电话" />
          </Form.Item>

          <Form.Item
            name="idCard"
            label="身份证号"
            rules={[
              { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号' }
            ]}
          >
            <Input placeholder="请输入身份证号" />
          </Form.Item>

          <Form.Item
            name="company"
            label="来访公司"
            rules={[{ required: true, message: '请输入来访公司' }]}
          >
            <Input placeholder="请输入来访公司" />
          </Form.Item>

          <Form.Item
            name="visitPurpose"
            label="访问目的"
            rules={[{ required: true, message: '请选择访问目的' }]}
          >
            <Select placeholder="请选择访问目的">
              <Option value="商务洽谈">商务洽谈</Option>
              <Option value="技术交流">技术交流</Option>
              <Option value="参观考察">参观考察</Option>
              <Option value="面试">面试</Option>
              <Option value="培训">培训</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="visitee"
            label="被访人"
            rules={[{ required: true, message: '请输入被访人' }]}
          >
            <Input placeholder="请输入被访人" />
          </Form.Item>

          <Form.Item
            name="visitTime"
            label="访问时间"
            rules={[{ required: true, message: '请选择访问时间' }]}
          >
            <RangePicker 
              showTime 
              format="YYYY-MM-DD HH:mm"
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="vehiclePlate"
            label="车牌号码"
          >
            <Input placeholder="请输入车牌号码（如有）" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 二维码模态框 */}
      <Modal
        title="访客二维码"
        open={qrModalVisible}
        onCancel={() => setQrModalVisible(false)}
        footer={null}
        width={400}
      >
        {selectedVisitor && (
          <div style={{ textAlign: 'center' }}>
            <QRCode 
              value={`visitor:${selectedVisitor.id}:${selectedVisitor.qrCode}`}
              size={200}
            />
            <div style={{ marginTop: 16 }}>
              <p><strong>访客:</strong> {selectedVisitor.name}</p>
              <p><strong>二维码:</strong> {selectedVisitor.qrCode}</p>
              <p><strong>有效期:</strong> {selectedVisitor.visitTime[0]} 至 {selectedVisitor.visitTime[1]}</p>
            </div>
          </div>
        )}
      </Modal>
    </MainLayout>
  )
}

